package com.zhanggm.springboot.springbootdemo05.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceHandler是前台访问的路径前缀
        //addResourceLocations挂载项目项目中的静态资源或本地路径
        registry.addResourceHandler("/images/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/img/")
                .addResourceLocations("file:C:\\local\\dist\\");
    }

    /**
     * 注册拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor);
//        registry.addInterceptor()
    }

    /**
     * 跨域：协议不同、主机不同、端口不同、路径不同时候，ajax请求是需要配置的。
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //允许所有来源
                .allowedOrigins("*")
                //允许所有方法：Get、Post、Put、Delete
                .allowedMethods("*")
                //允许所有的头信息
                .allowedHeaders("*")
                //是否需要跨域验证
                .allowCredentials(true)
                //认证过期时间：单位秒
                .maxAge(3600);
    }
}
